import types from "./mutation-types.js";
import rootTypes from "../../store/mutation-types.js";
import axios from "axios";
const store = {
  namespaced: true,
  state: {
    requested: false,
    movie_wall_datas: [],
    req_lock: false
  },
  mutations: {
    [types.ADD_MOVIE_WALL_DATAS](state, movie_wall_datas) {
      state.movie_wall_datas = state.movie_wall_datas.concat(movie_wall_datas);
    },
    [types.UPDATE_MOVIE_WALL_DATAS](state, movie_wall_datas) {
      state.movie_wall_datas = movie_wall_datas;
    },
    [types.UPDATE_REQUEST_STATUS](state, new_status) {
      state.requested = new_status;
    },
    [types.UPDATE_REQ_LOCK_STATUS](state, new_status) {
      state.req_lock = new_status;
    }
  },
  actions: {
    reqMovieWallDatas({ commit, state }) {
      if (state.req_lock) {
        return new Promise(resolve => {
          resolve();
        });
      }
      commit(types.UPDATE_REQ_LOCK_STATUS, true);
      return axios.get("/back-end/service/getWallDatas.php", {
        params: this.state.params
      });
    },
    async updateMovieWallDatas({ commit }) {
      commit(types.UPDATE_REQUEST_STATUS, false);
      commit(rootTypes.UPDATE_LAST_NOTE_VALUE, null, {
        root: true
      });
      commit(types.UPDATE_MOVIE_WALL_DATAS, []);
      try {
        let data = await this.dispatch("movie_wall/reqMovieWallDatas");
        if (
          data &&
          data.data &&
          data.data.datas &&
          data.data.datas.length > 0
        ) {
          commit(types.UPDATE_MOVIE_WALL_DATAS, data.data.datas);
        }
      // eslint-disable-next-line no-empty
      } catch (err) {}
      commit(types.UPDATE_REQUEST_STATUS, true);
      commit(types.UPDATE_REQ_LOCK_STATUS, false);
    },
    addMovieWallDatas({ commit, state }) {
      commit(
        rootTypes.UPDATE_LAST_NOTE_VALUE,
        state.movie_wall_datas[state.movie_wall_datas.length - 1],
        { root: true }
      );
      commit(
        rootTypes.UPDATE_LAST_NOTE_ID,
        state.movie_wall_datas[state.movie_wall_datas.length - 1].id,
        { root: true }
      );
      return new Promise(async (resolve, reject) => {
        try {
          let data = await this.dispatch("movie_wall/reqMovieWallDatas");
          if (
            data &&
            data.data &&
            data.data.datas &&
            data.data.datas.length > 0
          ) {
            commit(types.ADD_MOVIE_WALL_DATAS, data.data.datas);
            if (data.data.datas.length === 0) {
              resolve();
            }
          } else {
            reject();
          }
        } catch (err) {
          reject(err);
        }
        commit(types.UPDATE_REQ_LOCK_STATUS, false);
      });
    }
  }
};

export default store;
